import time
import requests
from res import *

clear_screen()
title()

def download_mp3(url , name, save_path):
    try:
        # 发送请求获取文件内容
        response = requests.get(url, stream=True)
        response.raise_for_status()  # 检查请求是否成功
        name = name.replace("/", "_")  # 替换文件名中的非法字符
        # 获取文件名
        file_name = "[酷我]" + name + ".mp3"
        file_path = os.path.join(save_path, file_name)

        # 写入文件
        with open(file_path, "wb") as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)

        print(f"文件已成功下载到 {file_path}")
        e = input('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except requests.exceptions.RequestException as e:
        print(f"下载失败：{e}")
        print('感谢使用!')
        e = input('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()
    except Exception as e:
        print(f"发生错误：{e}")
        print('感谢使用!')
        e = input('按回车键返回---->')
        clear_screen()
        os.system(f"{p()} main.py")
        exit()

def parse_json(num,data):
    name = data['data']['name']
    artist = data['data']['artist']
    url = data['data']['url']

    # print("歌曲id:", id)
    print(f'[{num}]'+"歌曲名:[", name,']          歌手:[',artist,']')

def get_song_json(api,song_name):
    if song_name.strip() == '':
        print("歌曲名为空或只包含空白字符")
        time.sleep(2.5)
        os.system(f'{p()} main.py')
        exit()
    else:
        song_name = song_name
    # if song_num == '':
    #     song_num = '1'
    # else:
    #     song_num = song_num
    song_num = 1
    json_url = f'{api}word={song_name}&n={str(song_num)}'
    response2 = requests.get(json_url)
    data2 = response2.json()
    json_url_dict = {}
    json_url_dict['1'] = json_url

    print('正在获取json_url......')
    while data2['data'] != 'null':
        song_num = song_num+1
        json_url = f'{api}word={song_name}&n={str(song_num)}'
        response2 = requests.get(json_url)
        data2 = response2.json()
        json_url_dict[f'{song_num}'] = json_url
        time.sleep(0.2)
        if song_num == 10:
            print('获取完成!')
            break

    return json_url_dict

song_name = input("请输入酷我音乐歌曲名称或歌手(区分大小写,空格用_代替): ")
#song_num = input('请输入页码(默认1):')
save_path = input('请输入下载路径,默认本文件夹下的music文件夹:')
if save_path != '':
    if not save_path.endswith('/'):
        save_path += '/'
else:
    save_path = 'music/酷我音乐/'
api = 'https://api.52vmy.cn/api/music/kw? '

json_url_dict = get_song_json(api,song_name)
print('json_url字典:',json_url_dict)
time.sleep(1.5)
clear_screen()
title()
json_dict = {}
print('获取数据中......')
for i in range(1,len(json_url_dict)+1):
    time.sleep(0.3)
    response = requests.get(json_url_dict[str(i)])
    json_dict[i] = response.json()
print('获取完成:')
for i in range(1,len(json_url_dict)+1):
    parse_json(f'{i}',json_dict[i])
choose = int(input('请选择:'))
time.sleep(1.5)
clear_screen()
title()
user_json = json_dict[choose]
name = user_json['data']['name']
artist = user_json['data']['artist']
id = user_json['data']['id']
picture = user_json['data']['picture']
url = user_json['data']['url']

print(f'\n歌曲名:{name}\n作者:{artist}\nid:{id}\n封面链接:{picture}\n下载连接:{url}')
download_mp3(url , song_name, save_path)